<?

include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');
include($_SERVER['DOCUMENT_ROOT'].'/filter.libs.php');

$bits = explode('.',$_SERVER['SERVER_NAME']);
$domain = $bits[0];

$row = getRow("SELECT portal_id,title,user_id,realname,readable FROM portal INNER JOIN user USING (user_id) WHERE domain = ".dbQuote($domain)." AND status_id = 1");

if (empty($row['portal_id'])) {
	header("HTTP/1.0 404 Not Found");
	print "<html><head>";
	print "<title>Not found!</title>";
	print "</head><body>";
	print "<p>The page you are looking for is not available</p>";
	
	print "<p><a href=\"http://www.geographs.org/portals/?ref=$domain\">Try the Portal Homepage</a></p>";
	print "</body></html>";
	print str_repeat(" ",500);
	exit;
}

$portal_id = $id = intval($row['portal_id']);
$title = $row['title'];

$row['count'] = count_active($id);

$page_title = "Breakdown";



customNoCacheHeader('',true);
customExpiresHeader(3600*24,true);


#########################
# Setup Defaults


$sql = array();
$sql['columns'] = 'SUBSTRING(imagetaken,1,4) AS name,COUNT(*) AS count';
$sql['tables'] = array();

$sql['tables'][] = "p2.gridimage{$id}_bi_view AS gi";


$sql['wheres'] = array();

$sql['group'] = "SUBSTRING(imagetaken,1,4)";
$sql['limit'] = 13;

#########################
# Possiblities and defaults

$view = 'text';
$by = 'year';
$bytitle = "Year Taken";
$filter = 'taken';
$pgsize = $sql['limit'];
$order = 'name';


$views = array(
'text' => '&middot; Text Listing',
'cloud' => '&middot; Word Cloud',
);

$bys = array(
'year' => 'Year Taken',
'yearmonth' => 'Year+Month Taken',
'month' => 'Month Taken',
'realname' => 'Contributor Name',
'user_id' => 'Contributor ID',
'category' => 'Category',
'mod' => 'Classification',
'myriad' => 'Myriad',
'hectad' => 'Hectad',
'cluster' => 'Automatic Cluster',
'cluster2' => 'Automatic Cluster2',
'term' => 'Terms',
'tag' => 'Tags',
##'gridref' => 'Grid Reference',
);

$orders = array(
'name' => 'Name/Title',
'count' => 'Count'
);

#########################
# Customise



if (!empty($_GET['by'])) {
	if ($_GET['by'] == 'user_id' || $_GET['by'] == 'realname') {
		$sql['columns'] = 'realname AS name,user_id AS value,COUNT(*) AS count';
		$sql['group'] = "user_id";
		$filter = "bi_id";
		$by = $_GET['by'];
	} elseif ($_GET['by'] == 'year') {
		$sql['columns'] = 'SUBSTRING(imagetaken,1,4) AS name,COUNT(*) AS count';
		$sql['group'] = "SUBSTRING(imagetaken,1,4)";
		$filter = "taken";
		$by = 'year';
	} elseif ($_GET['by'] == 'month') {
		$sql['columns'] = 'SUBSTRING(imagetaken,6,2) AS name,COUNT(*) AS count';
		$sql['group'] = "SUBSTRING(imagetaken,6,2)";
		$filter = "taken";
		$by = 'month';
	} elseif ($_GET['by'] == 'yearmonth') {
		$sql['columns'] = 'SUBSTRING(imagetaken,1,7) AS name,COUNT(*) AS count';
		$sql['group'] = "SUBSTRING(imagetaken,1,7)";
		$filter = "taken";
		$by = 'yearmonth';
	} elseif ($_GET['by'] == 'taken') {
		$sql['columns'] = 'imagetaken AS name,COUNT(*) AS count';
		$sql['group'] = "imagetaken";
		$filter = "taken";
		$by = 'taken';
	} elseif ($_GET['by'] == 'category') {
		$sql['columns'] = 'imageclass AS name,COUNT(*) AS count';
		$sql['group'] = "imageclass";
		$filter = "category";
		$by = 'category';
	} elseif ($_GET['by'] == 'canonical') {
		$sql['tables'][] = "INNER JOIN geograph_live.category_canonical AS cc USING (imageclass)";
		$sql['columns'] = 'canonical AS name,COUNT(*) AS count';
		$sql['group'] = "canonical";
		$filter = "canonical";
		$by = 'canonical';
	} elseif ($_GET['by'] == 'mod') {
		$sql['columns'] = 'moderation_status AS name,COUNT(*) AS count';
		$sql['group'] = "moderation_status";
		$filter = "mod";
		$by = 'mod';
	} elseif ($_GET['by'] == 'ftf') {
		$sql['columns'] = 'ftf AS name,COUNT(*) AS count';
		$sql['group'] = "ftf";
		$filter = "ftf";
		$by = 'ftf';
	} elseif ($_GET['by'] == 'myriad') {
		$sql['group'] = "SUBSTRING(gi.grid_reference,1,3 - reference_index)"; //TODO BI specific!
		$sql['columns'] = $sql['group'].' AS name,COUNT(*) AS count';
		$filter = "myriad";
		$by = 'myriad';
	} elseif ($_GET['by'] == 'hectad') {
		$sql['group'] = "concat(substring(gi.grid_reference,1,length(gi.grid_reference)-3),substring(gi.grid_reference,length(gi.grid_reference)-1,1))"; //TODO BI specific!
		$sql['columns'] = $sql['group'].' AS name,COUNT(*) AS count';
		$filter = "hectad";
		$by = 'hectad';
	} elseif ($_GET['by'] == 'gridref') {
		$sql['columns'] = 'moderation_status AS name,COUNT(*) AS count';
		$sql['group'] = "moderation_status";
		$filter = "gridref";
		$by = 'gridref';
		$bys['gridref'] = 'Grid Reference'; //we dont show it always!
	} elseif ($_GET['by'] == 'cluster') {
		$sql['tables'][] = "INNER JOIN geograph_live.gridimage_group AS gg USING (gridimage_id)";
		$sql['columns'] = 'label AS name,COUNT(*) AS count';
		$sql['group'] = "label";
		$filter = "cluster";
		$by = 'cluster';
	} elseif ($_GET['by'] == 'term') {
		$sql['tables']['gt'] = "INNER JOIN geograph_live.gridimage_term AS gt USING (gridimage_id)";
		$sql['columns'] = 'term AS name,COUNT(*) AS count';
		$sql['group'] = "term";
		$filter = "term";
		$by = 'term';
	} elseif ($_GET['by'] == 'cluster2') {
		$sql['tables'][] = "INNER JOIN gridimage_group AS gg USING (gridimage_id)";
		$sql['wheres'][] = "gg.portal_id = $portal_id";
		$sql['columns'] = 'label AS name,COUNT(*) AS count';
		$sql['group'] = "label";
		$filter = "cluster2";
		$by = 'cluster2';
	} elseif ($_GET['by'] == 'tag') {
		$sql['tables']['gt'] = "INNER JOIN p2.gridimage_tag{$portal_id}_bi_view AS gt USING (gridimage_id)";
		$sql['columns'] = 'gt.display AS name,COUNT(*) AS count';
		$sql['group'] = "tag";
		$filter = "tag";
		$by = 'tag';
	} 
} 

if (!empty($_GET['order'])) {
	if (!empty($_GET['in']) && strlen($_GET['in']) == 1) $in = $_GET['in'];
	$asc = ($in == 'a')?'asc':'desc';
	switch ($_GET['order']) {
		case 'count': $sql['order'] = "`count` $asc"; $order = 'count';break;
		case 'group': 
		     default:  
			if ($_GET['by'] == 'realname') {
				$sql['order'] = "`realname` $asc";
			} elseif ($asc == 'desc') {
				$sql['group'] .= " $asc";
			} 
			$order = 'group'; break;
	}
	$title = '';
}

#if ($sql['order'] == '`count` desc') {
	$views['wordle'] = '&middot; Wordle Maker';
#}

if (!empty($_GET['view'])) {
	
	if (isset($views[$_GET['view']])) {
		$view = $_GET['view'];
	}
} 


#########################
# paging

if (!empty($_GET['page'])) {
				
	$page = intval($_GET['page']);

	if (empty($page) || $page < 1) {$page = 1;}
	#if ($page > $numberOfPages) {$page = $numberOfPages;}

	$pg = ($page -1)* $pgsize;

	$sql['limit'] = "$pg,$pgsize";
} else {
	$page = 1;
	$pg = 0;
}

#########################
# Display results!

$query = sqlMakeQuery($sql);
if ($_GET['qq']) 
	print_rp($query);
	
		list($usec, $sec) = explode(' ',microtime());
		$querytime_before = ((float)$usec + (float)$sec);

if ($_GET['resort'])
	$query = "SELECT * FROM ($query) t1 ORDER BY name";

$result = queryExecute($query);

		list($usec, $sec) = explode(' ',microtime());
		$querytime_after = ((float)$usec + (float)$sec);

		if (($querytime_after-$querytime_before) > 0.1) {
			$hh = fopen("./slow.log",'a');
			fprintf($hh,"%0.4f,BREAK,%d,%d,%s\n",$querytime_after-$querytime_before,$portal_id,time(),str_replace(array("\n","\r"),' ',$query));
			fclose($hh);
		}

if ($result) {
	
	
		
	
		print "<table class=\"report\" style=\"width:200px;font-size:0.7em\">";
		#print "<tr>";
		#print "<th>{$bys[$by]}</th>";
		#print "<th>Count</th>";
		#print "</tr>";

		while($c = mysql_fetch_assoc($result)) {
			if (empty($c['value'])) {
				$c['value'] = $c['name'];
			}
			print "<tr>";
			$link = linktoself(array($filter=>$c['value'],'a'=>1,'delete'=>array('by','order','in')),'/');  //todo a=1 is temp
			print "<td><a href=\"$link\">".he($c['name'])."</a></td>";

			print "<td align=right>{$c['count']}</td>";

			print "</tr>";

		}
		print "</table>";
	
		//todo - temp
		$link = linktoself(array(),'/breakdown.php');  //todo a=1 is temp
		print "<small><a href=\"$link\">View more....</a></spam>";
} else {
	print "<p>No Images to show at this time.</p>";
}



#########

